<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Cate;

class CateController extends Controller
{
    public function index(){
    	$page = DB::table('category')->join('model', 'category.model_id', '=', 'model.model_id')->select('category.*', 'model.model_name')->paginate(20);
    	// 转换为数组
    	$list=$page->toArray();
    	// 无限级分类
    	$listArr=tree(array_map('get_object_vars',$list['data']));
		return view('admin.cate.index',['list'=>$listArr,'page'=>$page]);
    }
    public function add(Request $request){
    	if($request->isMethod('get')){
	    	$list=DB::table('model')->where('model_table','blog_info')->get();
	    	$cate=DB::table('category')->get();
			return  view('admin.cate.add',['list'=>$list,'cate'=>$cate]);
		}else{
			// 插入数据 返回插入数据的bool值
			$res = DB::table('category')->insert($request->except ('_token'));
			// 插入数据 返回插入数据的id
			// $bool = DB::table('model')->insertGetId($request->input());
			if($res){
				return redirect('cate/index');
			}else{
				echo '输入有误，后期优化用户体验！';
			}
		}
    }
    public function edit(Request $request,$id=null){
    	if($request->isMethod('get')){
    		if($id){
    			$res=DB::table('category')->where('cate_id', $id)->get();
		    	$list=DB::table('model')->where('model_table','blog_info')->get();
		    	$cate=DB::table('category')->get();
				return  view('admin.cate.edit',['res'=>$res[0],'list'=>$list,'cate'=>$cate]);
    		}else{
				return  abort('404');
    		}
		}else{
			// 插入数据 返回插入数据的bool值
			$res = DB::table('category')->where('cate_id',$request->input('id'))->update($request->except (['_token','id']));;
			if($res){
				return redirect('cate/index');
			}else{
				echo '输入有误，后期优化用户体验！';
			}
		}
    }
    public function del(Request $request){
    	if($request->input('id')){
			$res =DB::table('category')->where('cate_id',$request->input('id'))->delete();
			if($res){
				return 1;
			}else{
				return 2;
			}
    	}else{
			return  abort('404');
    	}
    }
}
